<?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH . '/libraries/pay/WxPay.Api.php';
require APPPATH . '/libraries/pay/PayNotifyCallBack.php';

//登陆之后通过session_key 访问的接口
class Info extends CI_Controller
{

	private $user_id;
	private $user_info;
	private $post;
	private $shopIds; //有距离的商铺id

	public function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->helper('json');
		$this->load->helper('common');
		$this->init();
	}

	private function init()
	{

		$this->post = $post = $this->input->post();
		$session_key = isset($post['session_key']) ? $post['session_key'] : 'cYI4nmRd8LlPhJ0V/0UpIA==';
		$this->requireRes($session_key, '缺少参数session_key');
		$this->user_info = $this->db->query("select * from app_user where session_key = '$session_key'")->row_array();
		$this->requireRes($this->user_info, '未找到用户信息');
		$this->user_id = $this->user_info['id'];
		$this->shopIds = $this->user_info['shop_ids'];
		$func = $this->router->fetch_method();
		switch ($func) {
			case 'dingwei':
			case 'getLocation':
				break;
			default:
				$this->requireRes($this->shopIds, '没有店铺信息');
				$this->shopIds = explode(",", $this->user_info['shop_ids']);
				break;
		}
	}

	//获取首页banner

	/**
	 * @SWG\Post(
	 *     summary="获取首页banner",
	 *     path="/info/getBanner",
	 *     tags={"商户端2.0"},
	 *     operationId="getBanner",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getBanner()
	{
		$this->sendOk($this->db->query("select * from app_banner order by sort asc")->result_array());
	}

	//获取首页展示的商品分类

	/**
	 * @SWG\Post(
	 *     summary="获取首页展示的商品分类",
	 *     path="/info/getCates",
	 *     tags={"商户端2.0"},
	 *     operationId="getCates",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getIndexCates()
	{
		$cates = $this->db->query("select * from app_category where is_index = 1")->result_array();
		$this->sendOk($cates);
	}

	//获取热门分类
	public function getHotCates()
	{
		$cates = $this->db->query("select * from app_category where is_hot = 1")->result_array();
		$this->sendOk($cates);
	}

	//获取所有分类
	public function getCates()
	{
		$cates = $this->db->query("select * from app_category")->result_array();
		$this->sendOk($cates);
	}

	//获取首页展示的类目和商品

	/**
	 * @SWG\Post(
	 *     summary="获取首页展示的类目和商品",
	 *     path="/info/getHeadCatesGoods",
	 *     tags={"商户端2.0"},
	 *     operationId="getHeadCatesGoods",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getHeadCatesGoods()
	{

		$sqlShopIds = implode(",", $this->shopIds);
		$res = $cates = $this->db->query("select id,name,path,banner from app_category where is_index = 1")->result_array();
		foreach ($cates as $k => $v) {
			$goods = $this->db->query("
                select
                id,goods_bn,title,price,num,unit,pic_4,category_id,(select sum(num) from app_shop_goods where app_shop_goods.goods_id=app_goods.id and app_shop_goods.num >0) as goods_num
                from
                app_goods
                where
                id in ( select goods_id from app_shop_goods where shop_id in (" . $sqlShopIds . ") and num >0 group by goods_id) and category_id = '{$v['id']}' and status = 1 limit 0,5
                ")->result_array();
			$res[$k]['goods'] = $goods;
		}
		$this->sendOk($res);

	}

	//根据商品分类获取商品列表
	//传入分类的id cateId
	/**
	 * @SWG\Post(
	 *     summary="根据商品分类获取商品列表",
	 *     path="/info/getGoodsByCate",
	 *     tags={"商户端2.0"},
	 *     operationId="getGoodsByCate",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="分类id",
	 *         in="formData",
	 *         name="cateId",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getGoodsByCate()
	{

		$post = $this->post;
		$cateId = isset($post['cateId']) ? $post['cateId'] : '';
		$this->requireRes($cateId, '');
		$sqlShopIds = implode(",", $this->shopIds);

		$this->sendOk($this->db->query("
            select
            id,goods_bn,title,price,num,unit,pic_4,(select sum(num) from app_shop_goods where app_shop_goods.goods_id=app_goods.id and app_shop_goods.num >0) as goods_num
            from
            app_goods
            where
            id
            in
            (
            select
            goods_id
            from
            app_shop_goods
            where
            shop_id
            in
            (" . $sqlShopIds . ") and num >0
            group by
            goods_id
            ) and category_id = '$cateId' and status = 1
            ")->result_array());
	}

	//商品搜索

	/**
	 * @SWG\Post(
	 *     summary="商品搜索",
	 *     path="/info/searchGoods",
	 *     tags={"商户端2.0"},
	 *     operationId="searchGoods",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="关键词",
	 *         in="formData",
	 *         name="keyword",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function searchGoods()
	{

		$post = $this->post;
		$keyword = isset($post['keyword']) ? $post['keyword'] : '';
		$sql = "";
		$keyword && $sql = " and title like '%{$keyword}%'";
		$sqlShopIds = implode(",", $this->shopIds);
		$data = $this->db->query("
            select
            id,goods_bn,title,price,unit,num,pic_4,(select sum(num) from app_shop_goods where app_shop_goods.goods_id=app_goods.id and app_shop_goods.num >0) as goods_num
            from
            app_goods
            where
            id
            in
            (
            select
            goods_id
            from
            app_shop_goods
            where
            shop_id
            in
            (" . $sqlShopIds . ") and num >0
            group by
            goods_id
            ) " . $sql . "
            ")->result_array();
		$this->requireRes($data, '未查询到数据');
		$this->sendOk($data);

	}

	//获取消息列表

	/**
	 * @SWG\Post(
	 *     summary="获取消息列表",
	 *     path="/info/getMessage",
	 *     tags={"商户端2.0"},
	 *     operationId="getMessage",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getMessage()
	{

		$userId = $this->user_id;
		$this->sendOk($this->db->query("select * from app_message where user_id = '$userId'")->result_array());
	}

	//获取收获地址

	/**
	 * @SWG\Post(
	 *     summary="获取收获地址",
	 *     path="/info/getAddress",
	 *     tags={"商户端2.0"},
	 *     operationId="getAddress",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getAddress()
	{

		$userId = $this->user_id;
		$this->sendOk($this->db->query("select * from app_address where user_id = '$userId'")->result_array());
	}

	//根据id获取收获地址

	/**
	 * @SWG\Post(
	 *     summary="根据id获取收获地址",
	 *     path="/info/getAddressById",
	 *     tags={"商户端2.0"},
	 *     operationId="getAddress",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="地址id",
	 *         in="formData",
	 *         name="id",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getAddressById()
	{

		$post = $this->post;
		$id = isset($post['id']) ? $post['id'] : '';
		$this->requireRes($id, '');
		$this->sendOk($this->db->query("select * from app_address where id = '$id'")->row_array());
	}

	//添加收获地址

	/**
	 * @SWG\Post(
	 *     summary="添加收获地址",
	 *     path="/info/addAddress",
	 *     tags={"商户端2.0"},
	 *     operationId="addAddress",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function addAddress()
	{

		$post = $this->post;
		$post['user_id'] = $this->user_id;
		unset($post['session_key']);
		$this->db->insert('app_address', $post);
		$id = $this->db->insert_id();
		$this->setDefaultAddress($id);
		$this->sendOk(array());
	}

	//删除地址

	/**
	 * @SWG\Post(
	 *     summary="删除地址",
	 *     path="/info/delAddress",
	 *     tags={"商户端2.0"},
	 *     operationId="delAddress",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="地址id",
	 *         in="formData",
	 *         name="id",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function delAddress()
	{

		$post = $this->post;
		$post['id'] = 15;
		$id = isset($post['id']) ? $post['id'] : '';
		$this->requireRes($id, '');
		$this->db->query("delete from app_address where id = '$id'");
		$this->sendOk(array());
	}

	//更新地址

	/**
	 * @SWG\Post(
	 *     summary="更新地址",
	 *     path="/info/updateAddress",
	 *     tags={"商户端2.0"},
	 *     operationId="updateAddress",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="地址id",
	 *         in="formData",
	 *         name="id",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function updateAddress()
	{

		$post = $this->post;
		$id = isset($post['id']) ? $post['id'] : '';
		$this->requireRes($id, '');
		unset($post['session_key']);
		unset($post['id']);
		$this->db->update('app_address', $post, "id = '$id'");
		$this->setDefaultAddress($id);
		$this->sendOk(array());
	}

	//设置默认地址

	/**
	 * @SWG\Post(
	 *     summary="设置默认地址",
	 *     path="/info/setDefaultAddress",
	 *     tags={"商户端2.0"},
	 *     operationId="setDefaultAddress",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="地址id",
	 *         in="formData",
	 *         name="id",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function setDefaultAddress($targetid)
	{

		$post = $this->post;
		$user_id = $this->user_id;
		if (!$targetid) {
			$id = isset($post['id']) ? $post['id'] : '';
		} else {
			$id = $targetid;
		}
		$this->requireRes($id, '');
		$this->db->update('app_address', array('is_default' => 0), "user_id = '$user_id'");
		$this->db->update('app_address', array('is_default' => 1), "id = '$id'");
		if (!$targetid) {
			$this->sendOk(array());
		}
	}

	//根据商品id获取商品详情

	/**
	 * @SWG\Post(
	 *     summary="根据商品id获取商品详情",
	 *     path="/info/getGoodsDetail",
	 *     tags={"商户端2.0"},
	 *     operationId="getGoodsDetail",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="商品id",
	 *         in="formData",
	 *         name="id",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getGoodsDetail()
	{

		$post = $this->post;
		$id = isset($post['id']) ? $post['id'] : '';
		$this->requireRes($id, '');
		$result = $this->db->query("select *,(select sum(num) from app_shop_goods where app_shop_goods.goods_id=app_goods.id and app_shop_goods.num >0) as goods_num  from app_goods where id = '$id'")->row_array();
		$result['detail'] = $this->db->query("select name,value from app_goods_detail where goods_id = '" . $result['id'] . "'")->result_array();
		$this->sendOk($result);
	}

	/**
	 * @SWG\Post(
	 *     summary="添加商品到购物车",
	 *     path="/info/mdyGoodsToCart",
	 *     tags={"商户端2.0"},
	 *     operationId="mdyGoodsToCart",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="商品id",
	 *         in="formData",
	 *         name="id",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="加减商品的标志1为加，2为减",
	 *         in="formData",
	 *         name="type",
	 *         required=true,
	 *         type="integer",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function mdyGoodsToCart()
	{

		$post = $this->post;
		$user_id = $this->user_id;
		$id = isset($post['id']) ? $post['id'] : '';
		$type = isset($post['type']) ? $post['type'] : '';
		$this->requireRes($id, '');
		//$exitNum = $this->getRefundGoodsNum($id);
		$exitNum = $this->getMaxGoodsNum($id);
		//先判断购物车中是否有这个商品
		$isSelectedGood = $this->db->query("select * from app_cart where type = 1 and user_id = '$user_id' and goods_id = '$id'")->row_array();
		if ($isSelectedGood) {
			if ($type == 1) {
				$isSelectedGood['num'] = $isSelectedGood['num'] + 1;
			} else {
				$isSelectedGood['num'] = $isSelectedGood['num'] - 1;
			}
			//判断是否超出库存
			if ($isSelectedGood['num'] > $exitNum) {
				send_json(
					array('code' => 4001, 'msg' => '超出库存数量', 'data' => '')
				);
			}
			//判断是否小于0
			if ($isSelectedGood['num'] < 1) {
				send_json(
					array('code' => 4001, 'msg' => '数量小于或者等于0', 'data' => '')
				);
			}

			$this->db->query("update app_cart set num = '{$isSelectedGood['num']}' where  type = 1 and user_id = '$user_id' and goods_id = '$id'");
		} else {

			//偶尔会发生这种情况
			if (1 > $exitNum) {
				send_json(
					array('code' => 4001, 'msg' => '超出库存数量', 'data' => '')
				);
			}

			$insert = array();
			$insert['type'] = 1;
			$insert['user_id'] = $user_id;
			$insert['goods_id'] = $id;
			$insert['num'] = 1;
			$this->db->insert('app_cart', $insert);
		}

		$this->getCartInfo();
	}

	/**
	 * @SWG\Post(
	 *     summary="获取购物车内容",
	 *     path="/info/getCartInfo",
	 *     tags={"商户端2.0"},
	 *     operationId="getCartInfo",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getCartInfo()
	{
		//返回购物车中的集合
		$user_id = $this->user_id;
		$this->sendOk($this->db->query("
                select
                    a.num as num,b.goods_bn as goods_bn,b.id as id,b.title as title,b.price as price,b.unit as unit,b.num as allNum,b.pic_4 as pic_4,(select sum(num) from app_shop_goods where app_shop_goods.goods_id=b.id and app_shop_goods.num >0) as goods_num
                from
                    app_cart a
                left join
                    app_goods b on a.goods_id = b.id
                where
                    a.user_id = '$user_id' and a.type = 1
                ")->result_array());
	}

	/**
	 * @SWG\Post(
	 *     summary="通过用户id获取订单列表",
	 *     path="/info/getOrderList",
	 *     tags={"商户端2.0"},
	 *     operationId="getOrderList",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getOrderList()
	{

		$user_id = $this->user_id;
		$post = $this->post;

		$status = isset($post['status']) ? " and  status= ${post['status']} " : '';

		$page = isset($post['page']) ? $post['page'] : 1;
		$start = ($page - 1) * 10;

		$list = $this->db->query("select * from app_order where user_id = '$user_id' $status  order by id desc limit $start,10")->result_array();


		foreach ($list as $key => $value) {
			if ($value['type'] == 1) {
				$list[$key]['goods'] = $this->db->query("
                    select
                        a.id as id,a.pic_4 as pic_4,b.num as num
                    from
                        app_goods a
                    left join
                        app_order_online_detail b on a.id=b.goods_id
                    left join
                        app_order_online c on c.id=b.online_id
                    where
                        c.order_id='{$value['id']}'
                    order by
                        a.id desc
                    ")->result_array();
			} else {
				$list[$key]['goods'] = $this->db->query("
                    select
                        a.id as id,a.pic_4 as pic_4,b.num as num
                    from
                        app_goods a
                    left join
                        app_order_offline_detail b on a.id=b.goods_id
                    where
                        b.order_id='{$value['id']}'
                    order by
                        a.id desc
                    ")->result_array();
			}
			$list[$key]['count'] = count($list[$key]['goods']);
		}
		$this->sendOk($list);
	}

	/**
	 * @SWG\Post(
	 *     summary="搜索订单",
	 *     path="/info/searchOrderList",
	 *     tags={"商户端2.0"},
	 *     operationId="searchOrderList",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="关键词",
	 *         in="formData",
	 *         name="keyword",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function searchOrderList()
	{
		$post = $this->post;

		$status = isset($post['status']) ? " and  status= ${post['status']} " : '';

		$page = isset($post['page']) ? $post['page'] : 1;
		$start = ($page - 1) * 10;

		$keyword = isset($post['keyword']) ? $post['keyword'] : '';
		$keyword = " and order_bn LIKE  '%{$keyword}%'";
		$user_id = $this->user_id;
		$list = $this->db->query("select * from app_order where user_id = '$user_id' {$keyword}  {$status} order by id desc  limit $start,10")->result_array();
		foreach ($list as $key => $value) {
			if ($value['type'] == 1) {
				$list[$key]['goods'] = $this->db->query("
                    select
                        a.id as id,a.pic_4 as pic_4,b.num as num
                    from
                        app_goods a
                    left join
                        app_order_online_detail b on a.id=b.goods_id
                    left join
                        app_order_online c on c.id=b.online_id
                    where
                        c.order_id='{$value['id']}'
                    order by
                        a.id desc
                    ")->result_array();
			} else {
				$list[$key]['goods'] = $this->db->query("
                    select
                        a.id as id,a.pic_4 as pic_4,b.num as num
                    from
                        app_goods a
                    left join
                        app_order_offline_detail b on a.id=b.goods_id
                    where
                        b.order_id='{$value['id']}'
                    order by
                        a.id desc
                    ")->result_array();
			}
			$list[$key]['count'] = count($list[$key]['goods']);
		}
		$this->sendOk($list);
	}

	//通过购物车id字符串获取商品信息,并且得到运费和礼品卡优惠券的数量
	public function goodsInfoBycartIdstr()
	{
		$user_id = $this->user_id;
		$post = $this->post;
		$post['cartIdStr'] = '1,2';
		$cartIdStr = isset($post['cartIdStr']) ? $post['cartIdStr'] : '';
		if (!$cartIdStr) {
			$this->requireRes('', '购物车为空');
		}
		$cartIdArr = explode(',', $cartIdStr);
		$goodsInfoArr = array();
		foreach ($cartIdArr as $key => $value) {
			$goodsInfoArr['goodsInfo'][] = $this->db->select('b.id as id,b.title as title,b.pic_4 as pic_4,b.goods_bn as goods_bn, b.price as price,b.unit as unit,b.description as description,a.num as num')->where(array('a.id' => $value, 'a.type' => 1, 'a.user_id' => $user_id))->from('app_cart a')
				->join('app_goods b', 'a.goods_id = b.id', 'left')
				->get()->result_array();
		}
		$this->db->where('start_time<', date('Y-m-d H:i:s', time()));
		$this->db->where('end_time>', date('Y-m-d H:i:s', time()));
		$this->db->where('user_id=', $user_id);
		$this->db->where('is_used=', 0);
		$couponNum = $this->db->from('app_user_coupon')->count_all_results();
		$this->db->where('user_id=', $user_id);
		$this->db->where('remain>', 0);
		$giftCardNum = $this->db->from('app_gift_card')->count_all_results();
		$goodsInfoArr['other']['couponNum'] = $couponNum;
		$goodsInfoArr['other']['giftCardNum'] = $giftCardNum;
		$freight = $this->db->where(array('k' => 'freight'))->from('app_key_value')->get()->row_array()['v'];
		$goodsInfoArr['other']['freight'] = $freight;
		$free_shipping = $this->db->where(array('k' => 'free_shipping'))->from('app_key_value')->get()->row_array()['v'];
		$goodsInfoArr['other']['free_shipping'] = $free_shipping;
		$this->sendOk($goodsInfoArr);
	}

	public function getA($allShopGoodsSort, $needGoods, $m)
	{
		$b = array();
		foreach ($allShopGoodsSort as $key => $value) {
			foreach ($needGoods as $k => $v) {
				if (isset($value[$k])) {
					if ($value[$k] >= $v) {
						$b[$key][] = $k;
					}
				}
			}
		}
		if (!count($b)) {
			return array('y' => $needGoods);
		}
		foreach ($b as $key => $value) {
			$a[count($value)][] = $key;
		}
		arsort($a);
		$x = array_shift($a);

		if (count($x) > 1) {
			foreach ($x as $key => $value) {
				$d[$value] = $m[$value];
			}
			asort($d);

			$x = key($d);
		} else {
			$x = $x[0];
		}
		$end[$x] = $b[$x];
		$y = array_diff(array_keys($needGoods), $b[$x]);
		$z = array();
		if (count($y)) {
			foreach ($y as $key => $value) {
				$z[$value] = $needGoods[$value];
			}
		}
		return array('x' => $x, 'b' => $b[$x], 'y' => $z);
	}

	//距离
	public function juli($latitude, $longitude)
	{
		$ShopIdStr = implode(",", $this->shopIds);
		require dirname(__FILE__) . '/../models/Map.php';
		$map = new Map();
		$from = $latitude . ',' . $longitude;

		$shops = $this->db->query("select * from app_shop where status = 1 and id in (" . $ShopIdStr . ")")->result_array();

		$shopIds = array();
		$i = 0;
		$to = '';
		foreach ($shops as $v) {
			$to .= $v['latitude'] . ',' . $v['longitude'] . ';';
			$shopIds[$i] = $v['id'];
			++$i;
		}

		$to = rtrim($to, ';');

		$res = $map->cejuli($from, $to);
		$res = json_decode($res, true);
		foreach ($res['result']['elements'] as $k => $v) {
			$s[] = array('k' => $k, 'd' => $v['distance']);
		}
		foreach ($s as $k => $row) {
			$volume[$k] = $row['d'];
			$edition[$k] = $row['k'];
		}

		//距离
		$m = array();
		foreach ($s as $k => $v) {
			$m[$shopIds[$v['k']]] = $v['d'];
		}
		return $m;
	}

	//下单
	public function makeOrder($param)
	{
		$cartids = $param['cartids'];
		$type = $param['type'];
		$latitude = $param['latitude'];
		$longitude = $param['longitude'];
		$couponId = $param['couponId'];
		$addressId = $param['addressId'];
		$giftCardId = $param['giftCardId'];
		$delivery_time = $param['delivery_time'];
		// $cartids       = '1,2,4';
		// $type          = 1;
		// $latitude      = '31.589064';
		// $longitude     = '120.305099';
		// $couponId      = '';
		// $addressId     = 3;
		// $giftCardId    = '';
		// $delivery_time = '';

		//获取购物车的信息
		$user_id = $this->user_id;
		$carts = $this->db->query("select a.*,b.price as price from app_cart a left join app_goods b on a.goods_id = b.id where a.user_id = '$user_id' and a.type = 1 and a.id in (" . $cartids . ")")->result_array();
		$money = 0;
		$couponMoney = 0;
		$giftCardMoney = 0;
		$needGoods = array();
		foreach ($carts as $key => $value) {
			$needGoods[$value['goods_id']] = $value['num'];
			//超出库存下单
			if ($value['num'] > $this->getRefundGoodsNum($value['goods_id'])) {
				$title = $this->db->where(array('id' => $value['goods_id']))->from('app_goods')->get()->row_array()['title'];
				$this->requireRes('', '商品-' . $title . '的库存不足');
			}
			$money += $value['price'] * $value['num'];
		}
		if ($couponId) {
			$couponMoney = $this->db->select('b.money')->where(array('a.coupon_id' => $couponId, 'a.is_used' => 0, 'a.user_id' => $user_id))->from('app_user_coupon a')
				->join('app_coupon b', 'a.coupon_id = b.id')
				->get()->row_array()['money'];
		}
		if ($giftCardId) {
			$giftCardMoney = $this->db->select('remain')->where(array('id' => $giftCardId))->from('app_gift_card')->get()->row_array()['remain'];
		}

		//扣除优惠券金额
		$deductCouponMoney = $money - $couponMoney;
		//送货上门是否免运费
		if ($type == 1) {
			$free_shipping = $this->db->where(array('k' => 'free_shipping'))->from('app_key_value')->get()->row_array()['v'];
			if ($deductCouponMoney < $free_shipping) {
				$freight = $this->db->where(array('k' => 'freight'))->from('app_key_value')->get()->row_array()['v'];
			} else {
				$freight = 0;
			}
		}

		//扣除礼品卡最终实付金额
		if ($giftCardMoney > ($deductCouponMoney + $freight)) {
			$realMoney = 0;
			$leftGiftCardUsed = $deductCouponMoney + $freight;
			$leftGiftCardMoney = $giftCardMoney - $leftGiftCardUsed;
		} else {
			$realMoney = $deductCouponMoney + $freight - $giftCardMoney;
			$leftGiftCardUsed = $giftCardMoney;
			$leftGiftCardMoney = 0;
		}
		$ShopIdStr = implode(",", $this->shopIds);

		//列出数组 存在的商品库存，以及数量
		$allShopGoods = $this->db->query("select * from app_shop_goods where shop_id in (" . $ShopIdStr . ")")->result_array();
		foreach ($allShopGoods as $key => $value) {
			$allShopGoodsSort[$value['shop_id']][$value['goods_id']] = $value['num'];
		}
		$m = $this->juli($latitude, $longitude);
		$r = $needGoods;
		$z = 0;
		$end = array();
		$j = array();
		while ($z == 0) {
			$left = $this->getA($allShopGoodsSort, $needGoods, $m);
			if (isset($left['x']) && $left['x']) {
				if (count($left['b'])) {
					$n = array();
					foreach ($left['b'] as $key => $value) {
						$j[] = $value;
						$n[$value] = $r[$value];
					}
				}
				$end[$left['x']] = $n;
				$needGoods = $left['y'];
				if (!count($needGoods)) {
					$z = 1;
				}
			} else {
				$z = 1;
			}
		}

		$o = array_diff(array_keys($r), $j);
		if (count($o)) {
			foreach ($o as $key => $value) {
				$title = $this->db->where(array('id' => $value))->from('app_goods')->get()->row_array()['title'];
				$this->requireRes('', '商品-' . $title . '的库存不足');
			}
		}
		$order_bn = trade_no();
		//生成订单
		$orderInfo = array();
		$orderInfo['user_id'] = $user_id;
		$orderInfo['order_bn'] = $order_bn;
		$orderInfo['type'] = 1;
		$orderInfo['money'] = $realMoney;
		$orderInfo['total_money'] = $money;
		$orderInfo['card_money'] = $leftGiftCardUsed;
		$orderInfo['coupon_money'] = $couponMoney;
		$orderInfo['freight'] = $freight;
		$orderInfo['address_id'] = $addressId;
		$orderInfo['delivery_method'] = $type;
		if ($delivery_time) {
			$orderInfo['delivery_time'] = $delivery_time;
		}
		if ($couponId) {
			$orderInfo['user_coupon_id'] = $couponId;
		}

		$orderInfo['status'] = 0;
		$orderInfo['created_at'] = date('Y-m-d H:i:S', time());
		$this->db->insert('app_order', $orderInfo);
		$orderId = $this->db->insert_id();
		$order_info = array();
		if ($orderId) {
			foreach ($end as $key => $value) {
				$this->db->insert('app_order_online', array('order_id' => $orderId, 'shop_id' => $key, 'status' => 0));
				$online_id = $this->db->insert_id();
				foreach ($value as $k => $v) {
					$this->db->insert('app_order_online_detail', array('online_id' => $online_id, 'goods_id' => $k, 'num' => $v));
				}
			}

			if ($couponId) {
				$this->db->where(array('coupon_id' => $couponId, 'user_id' => $user_id, 'is_used' => 0))->limit(1)->update('app_user_coupon', array('is_used' => 1, 'used_at' => date('Y-m-d H:i:s')));
			}

			if ($giftCardId) {
				$this->db->where(array('id' => $giftCardId, 'user_id' => $user_id))->update('app_gift_card', array('remain' => $leftGiftCardMoney));
				$this->db->insert('app_gift_card_order', array('card_id' => $giftCardId, 'order_id' => $orderId, 'created_at' => date('Y-m-d H:i:s'), 'money' => $leftGiftCardUsed));
			}
			$order_info['money'] = $money;
			$order_info['order_bn'] = $order_bn;
			$order_info['id'] = $orderId;
			return $order_info;
		} else {
			return false;

		}

	}

	//付钱(type=1 自提; type=2 送货上门)
	public function pay()
	{
		$post = $this->post();
		//数据
		$param['open_id'] = isset($post['open_id']) ? $post['open_id'] : '';
		$param['cartids'] = isset($post['cartids']) ? $post['cartids'] : '';
		$param['type'] = isset($post['type']) ? $post['type'] : '';
		$param['latitude'] = isset($post['latitude']) ? $post['latitude'] : '';
		$param['longitude'] = isset($post['longitude']) ? $post['longitude'] : '';
		$param['couponId'] = isset($post['couponId']) ? $post['couponId'] : '';
		$param['addressId'] = isset($post['addressId']) ? $post['addressId'] : '';
		$param['giftCardId'] = isset($post['giftCardId']) ? $post['giftCardId'] : '';
		$param['delivery_time'] = isset($post['delivery_time']) ? $post['delivery_time'] : '';

		if ($param['cartids'] && $param['type'] && $param['latitude'] && $param['longitude'] && $param['open_id']) {
			$orders = $this->makeOrder($param);
			if ($orders) {
				if (!$orders['money'] || $orders['money'] == 0) {
					$now = date("Y-m-d H:i:s");
					$this->db->where(array('id' => $orders['id']))->update('app_order', array('status' => 10, 'payment_at' => $now, 'payment_method' => 2));
					$this->paySuccessDelCartNum($orders['id']);
					send_json(array('code' => 2000, 'data' => array('data' => $orders['id']), 'msg' => "success"));
				} else {
					$order_bn = $orders['order_bn'];
					$open_id = $param['open_id'];
					$fee = $orders['money'] * 100;
					//         初始化值对象
					$input = new WxPayUnifiedOrder();
					//         文档提及的参数规范：商家名称-销售商品类目
					$input->SetBody("stack");
					//         订单号应该是由小程序端传给服务端的，在用户下单时即生成，demo中取值是一个生成的时间戳
					$input->SetOut_trade_no($order_bn);
					//         费用应该是由小程序端传给服务端的，在用户下单时告知服务端应付金额，demo中取值是1，即1分钱
					$input->SetTotal_fee($fee);
					$input->SetNotify_url($this->config->item('base_url') . "/info/notify"); //需要自己写的notify.php\
					$input->SetTrade_type("JSAPI");
					//         由小程序端传给后端或者后端自己获取，写自己获取到的，
					$input->SetOpenid($open_id);
					//        $input->SetOpenid($this->getSession()->openid);
					//         向微信统一下单，并返回order，它是一个array数组
					$order = WxPayApi::unifiedOrder($input);
					//         json化返回给小程序端
					header("Content-Type: application/json");
					return $this->getJsApiParameters($order, $orders['id']);
				}

			} else {
				send_json(array('code' => 4004, 'data' => '', 'msg' => "创建失败"));
			}
		} else {
			send_json(array('code' => 4000, 'data' => '', 'msg' => "缺少参数"));
		}
	}

	// 回调函数
	public function notify()
	{
		$notify = new PayNotifyCallBack();
		$notify->Handle(false);
		$now = date("Y-m-d H:i:s");
		$returnValues = $notify->GetValues();
		log_message('error', $now . '发生回调:' . json_encode($returnValues));
		//交易成功
		if (!empty($returnValues['return_code']) && $returnValues['return_code'] == 'SUCCESS') {
			// 解析xml
			libxml_disable_entity_loader(true);
			$postStr = $this->postdata(); //接收post数据
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$arr = $this->object2array($postObj); //对象转成数组
			log_message('error', $now . ' 支付完成，返回值:' . json_encode($arr));

			//商户逻辑处理，如订单状态更新为已支付
			$order_bn = $arr['out_trade_no'];
			$transaction_id = $arr['transaction_id'];
			// 判断流水号来源
			$where = array('order_bn' => $order_bn);
			$info = $this->db->where($where)->from('app_order')->get()->row_array();
			if ($info) {
				if ($info['total_money'] > $info['money']) {
					$payment_method = 3;
				} elseif ($info['total_money'] == $info['money']) {
					$payment_method = 1;
				}
				$this->db->where($where)->update('app_order', array('status' => 10, 'transaction_id' => $transaction_id, 'payment_at' => $now, 'payment_method' => $payment_method));
				$this->paySuccessDelCartNum($info['id']);
			}
		}

		echo $notify->ToXml(); //返回给微信确认
	}

	public function paySuccessDelCartNum($orderId)
	{
		$item = $this->db->select('shop_id,id')->where(array('order_id' => $orderId))->from('app_order_online')->get()->result_array();
		$info = array();
		foreach ($item as $key => $value) {
			$info[$value['shop_id']] = $this->db->select('goods_id,num')->where(array('online_id' => $value['id']))->from('app_order_online_detail')->get()->result_array();
		}
		foreach ($info as $key => $value) {
			foreach ($value as $k => $v) {
				//删除店铺库存
				$this->db->where(array('shop_id' => $key, 'goods_id' => $v['goods_id']))->set('num', 'num-' . $v['num'], false)->update('app_shop_goods');
				//删除总库存
				$this->db->where(array('id' => $v['goods_id']))->set('num', 'num-' . $v['num'], false)->update('app_goods');
			}
		}
	}

	private function getJsApiParameters($UnifiedOrderResult, $order_id)
	{

		//判断是否统一下单返回了prepay_id
		if (!array_key_exists("appid", $UnifiedOrderResult)
			|| !array_key_exists("prepay_id", $UnifiedOrderResult)
			|| $UnifiedOrderResult['prepay_id'] == "") {
			send_json(array('code' => -1, 'data' => $UnifiedOrderResult, 'msg' => "fail"));
			throw new WxPayException("参数错误");
		}

		$jsapi = new WxPayJsApiPay();
		$jsapi->SetAppid($UnifiedOrderResult["appid"]);
		$timeStamp = time();
		$jsapi->SetTimeStamp("$timeStamp");
		$jsapi->SetNonceStr(WxPayApi::getNonceStr());
		$jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
		$jsapi->SetSignType("MD5");
		$jsapi->SetPaySign($jsapi->MakeSign());
		$parameters = $jsapi->GetValues();
		$parameters['order_id'] = $order_id;
		send_json(array('code' => 2000, 'data' => array('data' => $parameters), 'msg' => "success"));
	}

	public function getZitiInfo()
	{
		$post = $this->post();
		$cartids = $post['cartids'];
		$latitude = $post['latitude'];
		$longitude = $post['longitude'];
		// $latitude  = '31.589064';
		// $longitude = '120.305099';
		// $cartids       = '1,2,4';

		$user_id = $this->user_id;
		$carts = $this->db->query("select a.*,b.price as price from app_cart a left join app_goods b on a.goods_id = b.id where a.user_id = '$user_id' and a.type = 1 and a.id in (" . $cartids . ")")->result_array();
		$needGoods = array();
		foreach ($carts as $key => $value) {
			$needGoods[$value['goods_id']] = $value['num'];
			//超出库存下单
			if ($value['num'] > $this->getRefundGoodsNum($value['goods_id'])) {
				$title = $this->db->where(array('id' => $value['goods_id']))->from('app_goods')->get()->row_array()['title'];
				$this->requireRes('', '商品-' . $title . '的库存不足');
			}
		}

		$ShopIdStr = implode(",", $this->shopIds);

		//列出数组 存在的商品库存，以及数量
		$allShopGoods = $this->db->query("select * from app_shop_goods where shop_id in (" . $ShopIdStr . ")")->result_array();
		foreach ($allShopGoods as $key => $value) {
			$allShopGoodsSort[$value['shop_id']][$value['goods_id']] = $value['num'];
		}
		$m = $this->juli($latitude, $longitude);
		$r = $needGoods;
		$z = 0;
		$end = array();
		$j = array();
		while ($z == 0) {
			$left = $this->getA($allShopGoodsSort, $needGoods, $m);
			if (isset($left['x']) && $left['x']) {
				if (count($left['b'])) {
					$n = array();
					foreach ($left['b'] as $key => $value) {
						$j[] = $value;
						$n[$value] = $r[$value];
					}
				}
				$end[$left['x']] = $n;
				$needGoods = $left['y'];
				if (!count($needGoods)) {
					$z = 1;
				}
			} else {
				$z = 1;
			}
		}

		$o = array_diff(array_keys($r), $j);
		if (count($o)) {
			foreach ($o as $key => $value) {
				$title = $this->db->where(array('id' => $value))->from('app_goods')->get()->row_array()['title'];
				$this->requireRes('', '商品-' . $title . '的库存不足');
			}
		}
		$info = array();
		foreach ($end as $key => $value) {
			$info[$key] = $this->db->select('name,address')->where(array('id' => $key))->from('app_shop')->get()->row_array();
			foreach ($value as $k => $v) {
				$info[$key][] = $this->db->select('id,pic_4,title,price')->where(array('id' => $k))->from('app_goods')->get()->row_array();
			}
		}

		$this->sendOk($info);

	}

	/**
	 * @SWG\Post(
	 *     summary="定位",
	 *     path="/info/dingwei",
	 *     tags={"商户端2.0"},
	 *     operationId="dingwei",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="经纬度",
	 *         in="formData",
	 *         name="from",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function dingwei()
	{
		$distance = $this->db->query("select v from app_key_value where k = 'delivery_area'")->row_array()['v'];
		$post = $this->post;
		$user_id = $this->user_id;
		$from = isset($post['from']) ? $post['from'] : '';
		$this->requireRes($from, '没有传入定位信息');
		require dirname(__FILE__) . '/../models/Map.php';
		$shops = $this->db->query("select * from app_shop where status = 1")->result_array();
		$shopIds = array();
		$i = 0;
		$to = '';
		foreach ($shops as $v) {
			$to .= $v['latitude'] . ',' . $v['longitude'] . ';';
			$shopIds[$i] = $v['id'];
			++$i;
		}

		$to = rtrim($to, ';');
		$map = new Map();
		$res = $map->cejuli($from, $to);
		$res = json_decode($res, true);
		$s = array();
		if ($res['status'] == 0) {
			foreach ($res['result']['elements'] as $k => $v) {
				if ((int)$v['distance'] < $distance) {
					$s[] = array('k' => $k, 'd' => $v['distance']);
				}
			}
			foreach ($s as $k => $row) {
				$volume[$k] = $row['d'];
				$edition[$k] = $row['k'];
			}
			//array_multisort($volume, SORT_ASC, $edition, SORT_ASC, $s);
			$m = array();
			foreach ($s as $k => $v) {
				$m[] = $shopIds[$v['k']];
			}
			$shopids = implode(",", $m);
			$this->db->query("update app_user set shop_ids = '$shopids' where id = '$user_id'");
			$this->sendOk(array());
		} else {
			$this->requireRes(array(), $res['message']);
		}
	}

	/**
	 * @SWG\Post(
	 *     summary="获取地名",
	 *     path="/info/getLocation",
	 *     tags={"商户端2.0"},
	 *     operationId="getLocation",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="经纬度",
	 *         in="formData",
	 *         name="from",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getLocation()
	{

		$post = $this->post;
		$from = isset($post['from']) ? $post['from'] : '';
		$this->requireRes($from, '没有传入定位信息');
		require dirname(__FILE__) . '/../models/Map.php';
		$map = new Map();
		$res = $map->getLocation($from);
		$res = json_decode($res, true);
		if ($res['status'] == 0) {
			$this->sendOk($res["result"]);
		} else {
			$this->requireRes(array(), $res['message']);
		}
	}

	/**
	 * @SWG\Post(
	 *     summary="搜索地名",
	 *     path="/info/searchLocation",
	 *     tags={"商户端2.0"},
	 *     operationId="searchLocation",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="地名",
	 *         in="formData",
	 *         name="from",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="关键词",
	 *         in="formData",
	 *         name="keyword",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function searchLocation()
	{

		$post = $this->post;
		$from = isset($post['from']) ? $post['from'] : '';
		$this->requireRes($from, '没有传入定位信息');
		$keyword = isset($post['keyword']) ? $post['keyword'] : '';
		$this->requireRes($keyword, '没有传入搜索关键词');
		require dirname(__FILE__) . '/../models/Map.php';
		$map = new Map();
		$res = $map->search($from, $keyword);
		$res = json_decode($res, true);
		if ($res['status'] == 0) {
			$this->sendOk($res["data"]);
		} else {
			$this->requireRes(array(), $res['message']);
		}
	}

	/**
	 * @SWG\Post(
	 *     summary="优惠券列表",
	 *     path="/info/getCouponList",
	 *     tags={"商户端2.0"},
	 *     operationId="getCouponList",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getCouponList()
	{
		$user_id = $this->user_id;
		$where = array('a.user_id' => $user_id, 'a.is_used' => 0);
		$couponList = $this->db->select('a.id as id,b.coupon_bn as coupon_bn,b.title as title,b.money as money,b.threshold as threshold,b.type as type,a.start_time as start_time,a.end_time as end_time')->where($where)->from('app_user_coupon a')
			->join('app_coupon b', 'a.coupon_id = b.id and b.status = 1')
			->get()->result_array();
		$this->sendOk($couponList);
	}

	/**
	 * @SWG\Post(
	 *     summary="礼品券列表",
	 *     path="/info/getGiftCarfList",
	 *     tags={"商户端2.0"},
	 *     operationId="getGiftCarfList",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function getGiftCarfList()
	{
		$user_id = $this->user_id;
		$this->db->where('user_id=' . $user_id);
		$this->db->where('status=1');
		$this->db->or_where('status=2');
		$giftCart = $this->db->from('app_gift_card')->get()->result_array();
		$this->sendOk($giftCart);
	}

	/**
	 * @SWG\Post(
	 *     summary="查询礼品卡余额",
	 *     path="/info/queryBalance",
	 *     tags={"商户端2.0"},
	 *     operationId="queryBalance",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="卡号",
	 *         in="formData",
	 *         name="card_bn",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function queryBalance()
	{
		$post = $this->post;
		$post['card_bn'] = '181017000002';
		if (!isset($post['card_bn'])) {
			$this->requireRes('', '卡号不可为空');
		}
		$user_id = $this->user_id;
		$this->db->where('user_id=' . $user_id);
		$this->db->where('card_bn="' . $post['card_bn'] . '"');
		$giftCart = $this->db->from('app_gift_card')->get()->row_array();
		$this->requireRes($giftCart, '卡号不存在');
		$this->sendOk($giftCart['remain']);
	}

	/**
	 * @SWG\Post(
	 *     summary="绑定礼品卡",
	 *     path="/info/bindGiftCard",
	 *     tags={"商户端2.0"},
	 *     operationId="bindGiftCard",
	 *     produces={"application/json"},
	 *     @SWG\Response(
	 *         response=200,
	 *         description="成功",
	 *     ),
	 *     @SWG\Response(
	 *         response="401",
	 *         description="参数不全",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="签名",
	 *         in="formData",
	 *         name="session_key",
	 *         required=true,
	 *         type="string",
	 *     ),
	 *     @SWG\Parameter(
	 *         description="卡号",
	 *         in="formData",
	 *         name="card_bn",
	 *         required=true,
	 *         type="string",
	 *     )
	 * )
	 */
	public function bindGiftCard()
	{
		$post = $this->post;
		if (!isset($post['card_bn'])) {
			$this->requireRes('', '卡号不可为空');
		}
		$where = array('card_bn' => $post['card_bn']);
		$giftCart = $this->db->where($where)->from('app_gift_card')->get()->row_array();
		$this->requireRes($giftCart, '卡号不存在');
		$this->db->where($where)->update('app_gift_card', array('user_id' => $this->user_id));
		$this->sendOk(array());
	}

	//取消订单
	public function cancelOrder()
	{
		$user_id = $this->user_id;
		$post = $this->post;
		if (!isset($post['id'])) {
			$this->requireRes('', '订单不存在');
		}
		$where = array('id' => $post['id'], 'user_id' => $user_id);
		$row = $this->db->select('id,user_coupon_id,card_money')->where($where)->from('app_order')->get()->row_array();
		if ($row['user_coupon_id']) {
			$where = array('id' => $row['user_coupon_id']);
			$this->db->where($where)->update('app_user_coupon', array('is_used' => 0, 'used_at' => null));
		}
		$where = array('order_id' => $row['id']);
		if ($cardInfo = $this->db->select('card_id')->where($where)->from('app_gift_card_order')->get()->row_array()) {
			$this->db->where($where)->update('app_gift_card_order', array('money' => 0));
			$where = array('id' => $cardInfo['card_id']);
			$this->db->where($where)->set('remain', 'remain+' . $row['card_money'], false)->update('app_gift_card');
		}
		$where = array('id' => $post['id'], 'user_id' => $user_id);
		$this->db->where($where)->update('app_order', array('status' => 50));
		$this->sendOk(array());
	}

	//确认收货
	public function confirm()
	{
		$user_id = $this->user_id;
		$post = $this->post;
		if (!isset($post['id'])) {
			$this->requireRes('', '订单不存在');
		}
		$where = array('id' => $post['id'], 'user_id' => $user_id);
		$this->db->where($where)->update('app_order', array('status' => 1));
		$this->sendOk(array());
	}

	//再次购买
	public function payAgain()
	{
		$user_id = $this->user_id;
		$post = $this->post;
		$post['id'] = 51;
		if (!isset($post['id'])) {
			$this->requireRes('', '订单不存在');
		}
		$list = $this->db->where(array('id' => $post['id'], 'user_id' => $user_id))->select('id')->from('app_order')->get()->row_array();

		$list['goodsInfo'] = $this->db->select('b.num as num,b.goods_id as goods_id')->where(array('a.order_id' => $list['id']))->from('app_order_online a')
			->join('app_order_online_detail b', 'a.id = b.online_id', 'left')
			->get()->result_array();
		foreach ($list['goodsInfo'] as $key => $value) {
			$where = array('goods_id' => $value['goods_id'], 'user_id' => $user_id, 'type' => 1);
			$row = $this->db->where($where)->from('app_cart')->get()->row_array();
			if ($row) {
				$this->db->where($where)->set('num', 'num+' . $value['num'], false)->update('app_cart');
			} else {
				$insert = array();
				$insert['type'] = 1;
				$insert['user_id'] = $user_id;
				$insert['goods_id'] = $value['goods_id'];
				$insert['num'] = $value['num'];
				$this->db->insert('app_cart', $insert);
			}
		}

		$this->sendOk(array());
	}

	//订单详情
	public function orderDetail()
	{
		$user_id = $this->user_id;
		$post = $this->post;
		$id = $post['id'];
		if (!isset($post['id'])) {
			$this->requireRes('', '订单不存在');
		}
		$list = $this->db->where(array('id' => $id, 'user_id' => $user_id))->select('id,order_bn,money,total_money,card_money,coupon_money,freight,address_id,tracking_number,payment_method,delivery_method,delivery_time,status,refund_status,created_at,payment_at,delivered_at,completed_at,refunded_at,closed_at')->from('app_order')->get()->row_array();

		$list['goodsInfo'] = $this->db->select('c.id as id, c.price as price, c.goods_bn as goods_bn, c.title as title, c.unit as unit, c.pic_4 as pic_4, b.num as num')->where(array('a.order_id' => $list['id']))->from('app_order_online a')
			->join('app_order_online_detail b', 'a.id = b.online_id', 'left')
			->join('app_goods c', 'c.id = b.goods_id')
			->get()->result_array();
		$this->sendOk($list);
	}

	//根据商品id获取商品库存数量
	private function getRefundGoodsNum($goodsId)
	{

		$sqlShopIds = implode(",", $this->shopIds);
		return $this->db->query("select SUM(num) as num from app_shop_goods where goods_id = '$goodsId' and shop_id in (" . $sqlShopIds . ")")->row_array()['num'];
	}

	//根据商品id获取店铺商品最大库存数量
	private function getMaxGoodsNum($goodsId)
	{

		$sqlShopIds = implode(",", $this->shopIds);
		return $this->db->query("select Max(num) as num from app_shop_goods where goods_id = '$goodsId' and shop_id in (" . $sqlShopIds . ")")->row_array()['num'];
	}

	//根据商品id,商户id 获取商品库存数量
	private function getRefundGoodsNumByShopid($goodsId, $shopid)
	{

		return $this->db->query("select num from app_shop_goods where goods_id = '$goodsId' and shop_id = '$shopid'")->row_array()['num'];
	}

	//返回成功信息
	private function sendOk($data)
	{

		$ret['code'] = 2000;
		$ret['msg'] = '';
		$ret['data'] = $data;
		send_json($ret);
	}

	//返回参数失败信息
	private function requireRes($s, $r)
	{

		if ($r) {
			if (!$s) {
				send_json(
					array('code' => 4004, 'msg' => $r, 'data' => '')
				);
			}
		} else {
			if (is_array($s)) {
				foreach ($s as $v) {
					$this->requireRes($v, '');
				}
			} else {
				if (!$s) {
					send_json(
						array('code' => 4000, 'msg' => '参数错误', 'data' => '')
					);
				}
			}
		}
	}
}
